package com.ldk.admin.controller;

import java.util.Calendar;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ldk.framework.entity.Driver;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.ldk.admin.common.LigerUIGridResult;
import com.ldk.admin.common.Result;
import com.ldk.admin.constants.FORM;
import com.ldk.admin.constants.SESSION;
import com.ldk.base.framework.common.CustomPageable;
import com.ldk.base.framework.util.SystemUtil;
import com.ldk.framework.entity.AdminUser;
import com.ldk.framework.entity.CashApply;
import com.ldk.framework.entity.TicketUser;
import com.ldk.framework.entity.User;
import com.ldk.framework.enums.CashApplyStatus;
import com.ldk.framework.enums.PlatformUserType;
import com.ldk.framework.service.ICashApplyService;
import com.ldk.framework.service.IDriverService;
import com.ldk.framework.service.ITicketUserService;
import com.ldk.framework.service.IUserService;


@Controller
@RequestMapping("/cashapply")
public class CashApplyController extends BaseController {
	/**
	 * 路由地址
	 */
	private final String route = "cashapply";
	/**
	 * 模块名称
	 */
	private final String module = "提现申请";
	
	@Autowired
	private ICashApplyService cashApplyService;
	@Autowired
	private IUserService userService;
	@Autowired
	private IDriverService driverService;
	@Autowired
	private ITicketUserService ticketUserService;
	
	@RequestMapping("/list")
	//public ModelAndView list(ModelMap map){
	public ModelAndView list(ModelMap map,HttpServletRequest request,
							 HttpServletResponse response){
		//session是否过期
		this.isExpired(request,response);
		
		setLinks(map, "", "", "司机"+module, "/"+route+"/list", "", "");
		Calendar calendar = Calendar.getInstance();
		String endTime = SystemUtil.getDateString(calendar.getTime(), "yyyy-MM-dd");
		
		calendar.add(Calendar.DAY_OF_MONTH, -2);
		String startTime = SystemUtil.getDateString(calendar.getTime(), "yyyy-MM-dd");
		
		map.addAttribute("startTime", startTime);
		map.addAttribute("endTime", endTime);
		map.addAttribute("route", route);
		map.addAttribute("module", module);

		//操作日志
		//this.insertOplog(request,module+"管理","","","查看",this.getAdminUserName(request).toString(),Long.parseLong(this.getAdminId(request).toString()), SystemUtil.getAllSeconds());

		if (this.getRoleId(request) == 6) {
			return new ModelAndView("/cash/listcashapply_sj");
		} else {
			return new ModelAndView("/cash/listcashapply");
		}
	}

	@RequestMapping("/list1")
	//public ModelAndView list(ModelMap map){
	public ModelAndView list1(ModelMap map,HttpServletRequest request,
							 HttpServletResponse response){
		//session是否过期
		this.isExpired(request,response);

		setLinks(map, "", "", "票务经理"+module, "/"+route+"/list1", "", "");
		Calendar calendar = Calendar.getInstance();
		String endTime = SystemUtil.getDateString(calendar.getTime(), "yyyy-MM-dd");

		calendar.add(Calendar.DAY_OF_MONTH, -2);
		String startTime = SystemUtil.getDateString(calendar.getTime(), "yyyy-MM-dd");

		map.addAttribute("startTime", startTime);
		map.addAttribute("endTime", endTime);
		map.addAttribute("route", route);
		map.addAttribute("module", module);

		//操作日志
		//this.insertOplog(request,module+"管理","","","查看",this.getAdminUserName(request).toString(),Long.parseLong(this.getAdminId(request).toString()), SystemUtil.getAllSeconds());

		if (this.getRoleId(request) == 6) {
			return new ModelAndView("/cash/listcashapply_sj");
		} else {
			return new ModelAndView("/cash/listcashapply1");
		}
	}
	
	@ResponseBody
	@RequestMapping("/getList")
	public LigerUIGridResult<CashApply> getList(@RequestParam(value="page",required=false,defaultValue="1") int page, 
									         @RequestParam(value="pagesize",required=false,defaultValue="10") int pageSize,
									         @RequestParam(value="startTime",required=false,defaultValue="")  String startTime,
									         @RequestParam(value="endTime",required=false,defaultValue="") String endTime,
									         @RequestParam(value="searchKey",required=false,defaultValue="") String searchKey,
									         HttpServletRequest request)
	{
		int limit = pageSize;
		int offset = (page -1) * pageSize;
		
		CashApply query = new CashApply();
		query.setApplyUserType(PlatformUserType.DRIVER_USER.getValue());
		query.setStatus(CashApplyStatus.Apply.getValue());
		if(!StringUtils.isEmpty(startTime)){
			long st = SystemUtil.stringToSeconds(startTime, "yyyy-MM-dd");
			query.setStartTime(st);
		}
		if(!StringUtils.isEmpty(endTime)){
			long et = SystemUtil.stringToSeconds(endTime, "yyyy-MM-dd");
			et += 24 * 3600;//增加一天的时间
			query.setEndTime(et);
		}
		if(!StringUtils.isEmpty(searchKey)){
			query.setSearchKey(searchKey);
		}
		CustomPageable pageable = new CustomPageable(offset, limit);
		
		long total = cashApplyService.selectCount("", query);
		List<CashApply> result = cashApplyService.selectList("", query, pageable);
		
		LigerUIGridResult<CashApply> grid = new LigerUIGridResult<>();
		grid.Total = total;
		grid.Rows = result;
		
		return grid;
	}

	@ResponseBody
	@RequestMapping("/getList1")
	public LigerUIGridResult<CashApply> getList1(@RequestParam(value="page",required=false,defaultValue="1") int page,
												@RequestParam(value="pagesize",required=false,defaultValue="10") int pageSize,
												@RequestParam(value="startTime",required=false,defaultValue="")  String startTime,
												@RequestParam(value="endTime",required=false,defaultValue="") String endTime,
												@RequestParam(value="searchKey",required=false,defaultValue="") String searchKey,
												HttpServletRequest request)
	{
		int limit = pageSize;
		int offset = (page -1) * pageSize;

		CashApply query = new CashApply();
		query.setApplyUserType(PlatformUserType.TICKET_USER.getValue());
		query.setStatus(CashApplyStatus.Apply.getValue());
		if(!StringUtils.isEmpty(startTime)){
			long st = SystemUtil.stringToSeconds(startTime, "yyyy-MM-dd");
			query.setStartTime(st);
		}
		if(!StringUtils.isEmpty(endTime)){
			long et = SystemUtil.stringToSeconds(endTime, "yyyy-MM-dd");
			et += 24 * 3600;//增加一天的时间
			query.setEndTime(et);
		}
		if(!StringUtils.isEmpty(searchKey)){
			query.setSearchKey(searchKey);
		}
		CustomPageable pageable = new CustomPageable(offset, limit);

		long total = cashApplyService.selectCount("", query);
		List<CashApply> result = cashApplyService.selectList("", query, pageable);

		LigerUIGridResult<CashApply> grid = new LigerUIGridResult<>();
		grid.Total = total;
		grid.Rows = result;

		return grid;
	}
	
	@RequestMapping("/audit/{applyId}")
	public ModelAndView audit(@PathVariable(value="applyId") long applyId, ModelMap map,HttpServletRequest request,
							  HttpServletResponse response){
		//session是否过期
		this.isExpired(request,response);
		setLinks(map, module+"管理", "/"+route+"/list", module+"审核", "/"+route+"/audit/"+applyId, "", "");
		setForm(map, "/"+route+"/submitAudit", null);
		CashApply query=new CashApply();
		query.setApplyId(applyId);
		CashApply model = cashApplyService.selectByKey("", query);
		if(model == null){
			return new ModelAndView("redirect:/"+route+"/list");
		}
		//用户
		if(model.getApplyUserType() != PlatformUserType.CLIENT_USER.getValue() &&
		   model.getApplyUserType() != PlatformUserType.DRIVER_USER.getValue() &&
				model.getApplyUserType() != PlatformUserType.TICKET_USER.getValue()){
			return new ModelAndView("redirect:/"+route+"/list");
		}
		double balance = 0;
		if(model.getApplyUserType() == PlatformUserType.DRIVER_USER.getValue()){
			Driver driver = driverService.getDriverByOpenId("", model.getApplyUser());
			if(driver == null){
				return new ModelAndView("redirect:/"+route+"/list");
			}
			balance = driver.getBalance();
		}
		else if(model.getApplyUserType() == PlatformUserType.CLIENT_USER.getValue()){
			User userquery = new User();
			userquery.setOpenId(model.getApplyUser());
			userquery.setEnabled(true);
			User user = userService.selectOne("", userquery);
			if(user == null){
				return new ModelAndView("redirect:/"+route+"/list");
			}
			balance = user.getBalance();
		}
		else if(model.getApplyUserType() == PlatformUserType.TICKET_USER.getValue()){
			TicketUser userquery = new TicketUser();
			userquery.setPhoneNo(model.getApplyUser());
			userquery.setEnabled(true);
			TicketUser ticketUser = ticketUserService.selectOne("", userquery);
			if(ticketUser == null){
				return new ModelAndView("redirect:/"+route+"/list");
			}
			balance = ticketUser.getBalance();
		}
		map.addAttribute("balance", balance);
		return new ModelAndView("/cash/cashapplyaudit","model",model);
	}

	@RequestMapping("/audit1/{applyId}")
	public ModelAndView audit1(@PathVariable(value="applyId") long applyId, ModelMap map,HttpServletRequest request,
							  HttpServletResponse response){
		//session是否过期
		this.isExpired(request,response);
		setLinks(map, "票务经理"+module, "/"+route+"/list1", module+"审核", "/"+route+"/audit1/"+applyId, "", "");
		setForm(map, "/"+route+"/submitAudit1", null);
		CashApply query=new CashApply();
		query.setApplyId(applyId);
		CashApply model = cashApplyService.selectByKey("", query);
		if(model == null){
			return new ModelAndView("redirect:/"+route+"/list1");
		}
		//用户
		if(model.getApplyUserType() != PlatformUserType.CLIENT_USER.getValue() &&
				model.getApplyUserType() != PlatformUserType.DRIVER_USER.getValue() &&
				model.getApplyUserType() != PlatformUserType.TICKET_USER.getValue()){
			return new ModelAndView("redirect:/"+route+"/list1");
		}
		double balance = 0;
		if(model.getApplyUserType() == PlatformUserType.DRIVER_USER.getValue()){
			Driver driver = driverService.getDriverByOpenId("", model.getApplyUser());
			if(driver == null){
				return new ModelAndView("redirect:/"+route+"/list1");
			}
			balance = driver.getBalance();
		}
		else if(model.getApplyUserType() == PlatformUserType.CLIENT_USER.getValue()){
			User userquery = new User();
			userquery.setOpenId(model.getApplyUser());
			userquery.setEnabled(true);
			User user = userService.selectOne("", userquery);
			if(user == null){
				return new ModelAndView("redirect:/"+route+"/list1");
			}
			balance = user.getBalance();
		}
		else if(model.getApplyUserType() == PlatformUserType.TICKET_USER.getValue()){
			TicketUser userquery = new TicketUser();
			userquery.setPhoneNo(model.getApplyUser());
			userquery.setEnabled(true);
			TicketUser user = ticketUserService.selectOne("", userquery);
			if(user == null){
				return new ModelAndView("redirect:/"+route+"/list1");
			}
			balance = user.getBalance();
		}
		map.addAttribute("balance", balance);
		return new ModelAndView("/cash/cashapplyaudit1","model",model);
	}
	
	@RequestMapping("/submitAudit")
	public ModelAndView submitAudit(@RequestParam(value="applyId",required=true,defaultValue="0") long applyId,
									@RequestParam(value="status",required=true,defaultValue="0") int status,
									RedirectAttributes redAttr, ModelMap map, HttpServletRequest request,
									HttpServletResponse response){
		//session是否过期
		this.isExpired(request,response);
		Result rst = new Result();
		redAttr.addFlashAttribute(FORM.FROM_RESULT, rst);
		redAttr.addAttribute("applyId", applyId);
		AdminUser admin = (AdminUser)request.getSession().getAttribute(SESSION.USER);
		if(admin == null){
			return new ModelAndView("redirect:/login");
		}
		CashApply query=new CashApply();
		query.setApplyId(applyId);
		CashApply model = cashApplyService.selectByKey("", query);
		if(model == null){
			return new ModelAndView("redirect:/"+route+"/list");
		}
		//
		/*if(status < CashApplyStatus.Success.getValue()){
			return new ModelAndView("redirect:/"+route+"/audit/{applyId}");
		}*/
		int userType = model.getApplyUserType();
		String openId = model.getApplyUser();
		Double applyCash = model.getApplyCash();
		
		//如果审核成需要做余额等判断
		if(status == CashApplyStatus.Success.getValue()){
			if(userType != PlatformUserType.CLIENT_USER.getValue() &&
			   userType != PlatformUserType.DRIVER_USER.getValue()&&
					userType != PlatformUserType.TICKET_USER.getValue()){
				rst.AddError("用户类型错误");
				return new ModelAndView("redirect:/"+route+"/audit/{applyId}");
			}
			if(StringUtils.isEmpty(openId)){
				rst.AddError("申请提现用户手机号为空");
				return new ModelAndView("redirect:/"+route+"/audit/{applyId}");
			}
			if(applyCash <= 0){
				rst.AddError("申请提现金额不能小于0");
				return new ModelAndView("redirect:/"+route+"/audit/{applyId}");
			}
			//用户申请提现，判断用户余额是否足够
			if(userType == PlatformUserType.CLIENT_USER.getValue()){
				User user = userService.getUserByOpenId("", openId);
				if(user == null){
					rst.AddError("用户不存在，无法提现");
					return new ModelAndView("redirect:/"+route+"/audit/{applyId}");
				}
				//申请提现金额大于用户余额
				if(applyCash.compareTo(user.getBalance()) == 1){
					rst.AddError("用户余额不足，无法提现");
					return new ModelAndView("redirect:/"+route+"/audit/{applyId}");
				}
			}//司机申请提现，判断其账户余额是否足够
			else if(userType == PlatformUserType.DRIVER_USER.getValue()){
				Driver driver = driverService.getDriverByOpenId("", openId);
				if(driver == null){
					rst.AddError("司机不存在，无法提现");
					return new ModelAndView("redirect:/"+route+"/audit/{applyId}");
				}
				//申请提现金额大于服务人员余额
				if(applyCash.compareTo(driver.getBalance()) == 1){
					rst.AddError("服务人员余额不足，无法提现");
					return new ModelAndView("redirect:/"+route+"/audit/{applyId}");
				}
			}
			else if(userType == PlatformUserType.TICKET_USER.getValue()){
				TicketUser ticketUser = ticketUserService.getTicketInfoByPhoneNo("", openId);
				if(ticketUser == null){
					rst.AddError("票务经理不存在，无法提现");
					return new ModelAndView("redirect:/"+route+"/audit/{applyId}");
				}
				//申请提现金额大于服务人员余额
				if(applyCash.compareTo(ticketUser.getBalance()) == 1){
					rst.AddError("服务人员余额不足，无法提现");
					return new ModelAndView("redirect:/"+route+"/audit/{applyId}");
				}
			}
		}
		//验证过后赋值状态
		model.setStatus(status);

		Boolean succeed = false;
		try{
			this.insertOplog(request,module,"","","审核:"+model.getApplyUser(),this.getAdminUserName(request).toString(),
					Long.parseLong(this.getAdminId(request).toString()), SystemUtil.getAllSeconds());

			succeed = cashApplyService.submitAudit("", model, admin.getTrueName());
		}
		catch(Exception e){
			logger.error(e.getMessage());
		}
		if(succeed){
			rst.AddOk("审核操作成功");
		}
		else{
			rst.AddError("审核操作失败");
		}
		
		return new ModelAndView("redirect:/"+route+"/audit/{applyId}");
	}

	@RequestMapping("/submitAudit1")
	public ModelAndView submitAudit1(@RequestParam(value="applyId",required=true,defaultValue="0") long applyId,
									@RequestParam(value="status",required=true,defaultValue="0") int status,
									RedirectAttributes redAttr, ModelMap map, HttpServletRequest request,
									HttpServletResponse response){
		//session是否过期
		this.isExpired(request,response);
		Result rst = new Result();
		redAttr.addFlashAttribute(FORM.FROM_RESULT, rst);
		redAttr.addAttribute("applyId", applyId);
		AdminUser admin = (AdminUser)request.getSession().getAttribute(SESSION.USER);
		if(admin == null){
			return new ModelAndView("redirect:/login");
		}
		CashApply query=new CashApply();
		query.setApplyId(applyId);
		CashApply model = cashApplyService.selectByKey("", query);
		if(model == null){
			return new ModelAndView("redirect:/"+route+"/list1");
		}
		//
		/*if(status < CashApplyStatus.Success.getValue()){
			return new ModelAndView("redirect:/"+route+"/audit/{applyId}");
		}*/
		int userType = model.getApplyUserType();
		String openId = model.getApplyUser();
		Double applyCash = model.getApplyCash();

		//如果审核成需要做余额等判断
		if(status == CashApplyStatus.Success.getValue()){
			if(userType != PlatformUserType.CLIENT_USER.getValue() &&
					userType != PlatformUserType.DRIVER_USER.getValue()&&
					userType != PlatformUserType.TICKET_USER.getValue()){
				rst.AddError("用户类型错误");
				return new ModelAndView("redirect:/"+route+"/audit1/{applyId}");
			}
			if(StringUtils.isEmpty(openId)){
				rst.AddError("申请提现用户手机号为空");
				return new ModelAndView("redirect:/"+route+"/audit1/{applyId}");
			}
			if(applyCash <= 0){
				rst.AddError("申请提现金额不能小于0");
				return new ModelAndView("redirect:/"+route+"/audit1/{applyId}");
			}
			//用户申请提现，判断用户余额是否足够
			if(userType == PlatformUserType.CLIENT_USER.getValue()){
				User user = userService.getUserByOpenId("", openId);
				if(user == null){
					rst.AddError("用户不存在，无法提现");
					return new ModelAndView("redirect:/"+route+"/audit1/{applyId}");
				}
				//申请提现金额大于用户余额
				if(applyCash.compareTo(user.getBalance()) == 1){
					rst.AddError("用户余额不足，无法提现");
					return new ModelAndView("redirect:/"+route+"/audit1/{applyId}");
				}
			}//司机申请提现，判断其账户余额是否足够
			else if(userType == PlatformUserType.DRIVER_USER.getValue()){
				Driver driver = driverService.getDriverByOpenId("", openId);
				if(driver == null){
					rst.AddError("司机不存在，无法提现");
					return new ModelAndView("redirect:/"+route+"/audit1/{applyId}");
				}
				//申请提现金额大于服务人员余额
				if(applyCash.compareTo(driver.getBalance()) == 1){
					rst.AddError("服务人员余额不足，无法提现");
					return new ModelAndView("redirect:/"+route+"/audit1/{applyId}");
				}
			}
			else if(userType == PlatformUserType.TICKET_USER.getValue()){
				TicketUser ticketUser = ticketUserService.getTicketInfoByPhoneNo("", openId);
				if(ticketUser == null){
					rst.AddError("票务经理不存在，无法提现");
					return new ModelAndView("redirect:/"+route+"/audit1/{applyId}");
				}
				//申请提现金额大于服务人员余额
				if(applyCash.compareTo(ticketUser.getBalance()) == 1){
					rst.AddError("服务人员余额不足，无法提现");
					return new ModelAndView("redirect:/"+route+"/audit1/{applyId}");
				}
			}
		}
		//验证过后赋值状态
		model.setStatus(status);

		Boolean succeed = false;
		try{
			this.insertOplog(request,module,"","","审核:"+model.getApplyUser(),this.getAdminUserName(request).toString(),
					Long.parseLong(this.getAdminId(request).toString()), SystemUtil.getAllSeconds());

			succeed = cashApplyService.submitAudit("", model, admin.getTrueName());
		}
		catch(Exception e){
			logger.error(e.getMessage());
		}
		if(succeed){
			rst.AddOk("审核操作成功");
		}
		else{
			rst.AddError("审核操作失败");
		}

		return new ModelAndView("redirect:/"+route+"/audit1/{applyId}");
	}
	
}
